package com.xy.smartsms.plugincmcc;

import android.content.Context;

import com.xy.smartsms.data.SmsItem;
import com.xy.smartsms.util.Log;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import cn.cmcc.online.smsapi.SmsCardData;
import cn.cmcc.online.smsapi.TerminalApi;

import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * Created by admin on 2017/3/30.
 */

public class CardCallable implements Callable<SmsCardData> {
    private static final String TAG = CardCallable.class.getSimpleName();

    private Context context = null;
    private SmsItem item = null;
    private ExecutorService executor = newFixedThreadPool(1);
    private boolean mIsTimeout = false;

    public CardCallable(Context context) {
        this.context = context;
    }

    public void setItem(SmsItem item) {
        this.item = item;
    }

    @Override
    public SmsCardData call() throws Exception {
        SmsCardData cardData = TerminalApi.getCardDataManager().getCardData(context,
                item.getPhone(),
                item.getBody(),
                item.getReceiveTime(),
                null,
                false);
        return cardData;
    }

    public boolean isTimeout() {
        return mIsTimeout;
    }

    public SmsCardData executeWithTimeout(int timeout) {
        SmsCardData cardData = null;
        mIsTimeout = false;
        Future<SmsCardData> future = executor.submit(this);
        try {
            cardData = future.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException timeoutException) {
            mIsTimeout = true;
        } catch (Throwable t) {
            Log.e(TAG, "executeWithTimeout", t);
        }

        return cardData;
    }
}
